//
//  EWPreOrderViewController.m
//  haveSomethingToEat
//
//  Created by 陈 宁权 on 2017/7/27.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "EWPreOrderViewController.h"
#import "EWPreOrderBottomView.h"
#import "ViewModel.h"
#import "EWOrderInfoCell.h"

@interface EWPreOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIDatePicker *dataPicker;
@end

@implementation EWPreOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //配置导航栏
    [self configNavigation];
    //配置tableView
    [self configTableView];
    //添加底部面板
    [self addBottomView];
}

- (void)configNavigation
{
    self.navigationItem.title = @"订餐信息";
}

- (void)configTableView
{
    CGRect tableViewFrame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height -50);
    self.tableView = [[UITableView alloc] initWithFrame:tableViewFrame style:UITableViewStyleGrouped];
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)addBottomView
{
    EWPreOrderBottomView *bottomView = [[EWPreOrderBottomView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height -50, kScreenW, 50)];
    bottomView.prices = [NSString stringWithFormat:@"%.2f",[ViewModel GetTotalPrice:self.orderList]];
    bottomView.preOrderBtnClick = ^{//点击了预订按钮
        
    };
    [self.view addSubview:bottomView];
}

#pragma mark 代理方法

#pragma mark tableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }else if (section == 1){
        return self.orderList.count;
    }
    else{
        return 0;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        EWOrderInfoCell *cell = [EWOrderInfoCell cellWithTableView:tableView];
        [cell.logoView sd_setImageWithURL:[NSURL URLWithString:self.businessInfo.portraitUri]];
        cell.logoView.layer.cornerRadius = 8.5f;
        cell.logoView.layer.masksToBounds = YES;
        cell.titleLabel.text = self.businessInfo.businessName;
        return cell;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        EWOrderInfoCell *cell = [EWOrderInfoCell cellWithTableView:tableView];
        if (indexPath.row == 0) {
            cell.logoView.image = [[UIImage imageNamed:@"定位"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            cell.titleLabel.text = self.businessInfo.address;
            cell.needUnderLine = YES;
        }else if (indexPath.row == 1){
            cell.logoView.image = [[UIImage imageNamed:@"time"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            //根据距离商家距离大概估算花费在路上的时间出来
            [[BQLocationManager sharedManager] startUpdatingLocation];
            CLLocation *businessLocate = [[CLLocation alloc] initWithLatitude:[self.businessInfo.latitude doubleValue] longitude:[self.businessInfo.longitude doubleValue]];
            CLLocationDistance kilometers=[[BQLocationManager sharedManager].location distanceFromLocation:businessLocate]/1000;
            //获取预估到达时间
            NSDate *date1 = [NSDate date];
            NSTimeZone *zone = [NSTimeZone systemTimeZone];
            NSInteger interval = [zone secondsFromGMTForDate: date1];
            NSDate *localeDate = [date1  dateByAddingTimeInterval: interval];
            NSTimeInterval currentTime = [localeDate timeIntervalSince1970];
            NSTimeInterval expectTime = currentTime + (kilometers - 1) * 240 + 600;
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:expectTime];
            NSString *arrivalTime = @"";
            NSString *titleStr = @"";
            if (_dataPicker.date == nil || [_dataPicker.date isEqualToDate:date]) {
                arrivalTime = [NSString stringWithFormat:@"%@",[self compareDate:date]];
                titleStr = [NSString stringWithFormat:@"立即出发(大约%@到达)",[self compareDate:date]];
            }else{
                arrivalTime = [NSString stringWithFormat:@"%@",[self compareDate:_dataPicker.date]];
                titleStr = [NSString stringWithFormat:@"稍后出发(大约%@到达)",[self compareDate:_dataPicker.date]];
            }
            NSMutableAttributedString *titleAttributeStr = [[NSMutableAttributedString alloc] initWithString:titleStr];
            NSRange range = [titleStr rangeOfString:[NSString stringWithFormat:@"(大约%@到达)",arrivalTime]];
            [titleAttributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
            cell.titleLabel.attributedText = titleAttributeStr;
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    return [[UITableViewCell alloc] init];
}

- (NSString *)compareDate:(NSDate *)date{
    
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    
    //修正8小时之差
    NSDate *date1 = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date1];
    NSDate *localeDate = [date1  dateByAddingTimeInterval: interval];
    
//    NSLog(@"nowdate=%@\nolddate = %@",localeDate,date);
    NSDate *today = localeDate;
    NSDate *tomorrow,*afterOfTomorrow;
    //今年
    NSString *toYears;
    
    toYears = [[today description] substringToIndex:4];
    
    tomorrow = [today dateByAddingTimeInterval: secondsPerDay];
    afterOfTomorrow = [tomorrow dateByAddingTimeInterval: secondsPerDay];
    
    // 10 first characters of description is the calendar date:
    NSString *todayString = [[today description] substringToIndex:10];
    NSString *tomorrowString = [[tomorrow description] substringToIndex:10];
    NSString *afterOfTomorrowString = [[afterOfTomorrow description] substringToIndex:10];
    
    NSString *dateString = [[date description] substringToIndex:10];
    NSString *dateYears = [[date description] substringToIndex:4];
    
    NSString *dateContent;
    if ([dateYears isEqualToString:toYears]) {//同一年
        //今 昨 前天的时间
        NSString *time = [[date description] substringWithRange:(NSRange){11,5}];
        //其他时间
        NSString *time2 = [[date description] substringWithRange:(NSRange){5,11}];
        if ([dateString isEqualToString:todayString]){
            dateContent = [NSString stringWithFormat:@"今天 %@",time];
            return dateContent;
        } else if ([dateString isEqualToString:tomorrowString]){
            dateContent = [NSString stringWithFormat:@"明天 %@",time];
            return dateContent;
        }else if ([dateString isEqualToString:afterOfTomorrowString]){
            dateContent = [NSString stringWithFormat:@"后天 %@",time];
            return dateContent;
        }else{
            return time2;
        }
    }else{
        return dateString;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 1) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            //点击确定按钮的事件处理
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
        
        _dataPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(-17, 0, kScreenW, 200)];
        _dataPicker.datePickerMode = UIDatePickerModeDateAndTime;
        _dataPicker.minuteInterval = 5;
        NSDate *date1 = [NSDate date];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate: date1];
        NSDate *localeDate = [date1  dateByAddingTimeInterval: interval];
        _dataPicker.minimumDate = localeDate;
        [_dataPicker setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
        [_dataPicker setDate:[NSDate date] animated:YES];
        [alertController.view addSubview:_dataPicker];
        [alertController addAction:cancel];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
